/*******************************************************************************
 * Copyright (c) 2012 Evelina Vrabie
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 *******************************************************************************/
package activities;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.codeandmagic.android.gauge.GaugeView;
import org.codeandmagic.android.gauge.demo.R;

import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.GraphView.GraphViewData;
import com.jjoe64.graphview.GraphViewDataInterface;
import com.jjoe64.graphview.GraphViewSeries;
import com.jjoe64.graphview.LineGraphView;

import commons.AsyncTaskPage;
import commons.DataUlities;
import commons.DatePickerFragment;
import commons.ItemAdapterSpin;
import database.DataRecordDAO;
import database.DatabaseUtility;
import database.DeviceProfileDAO;
import database.UserProfileDAO;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends FragmentActivity {
	private GaugeView mGaugeView1, mGaugeView11, mGaugeView2, mGaugeView22,
			mGaugeView3, mGaugeView33;
	private GraphView graphView;
	private GraphViewSeries graphViewSeries1, graphViewSeries2,
			graphViewSeries3;
	private List<Integer> v1, v2, v3;
	private static String USER = "user";
	private static String DEVICE = "device";
	private Calendar cal;
	private List<String> userList, deviceList, listTime;
	private int day, month, year, dataSize;
	DataUlities util;
	private Spinner spnUser, spnDevice;
	public Button btn;
	private AsyncTaskPage mTask;
	@Override
	public void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_main);
		v1 = new ArrayList<Integer>();
		v2 = new ArrayList<Integer>();
		v3 = new ArrayList<Integer>();
		listTime = new ArrayList<String>();
		// create database
		DatabaseUtility database = new DatabaseUtility(MainActivity.this);
		database.open();
		database.close();
		util = new DataUlities(getApplicationContext());
		// get user and device
		initUserAndDevice();
		// gauge graph
		initGauge();
		// line graph
		initGraph();
		// init time
		initDateTime();
		btn = (Button) findViewById(R.id.btnStart);
		btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				// USER = spnUser.getSelectedItem().toString();
				// DEVICE = spnDevice.getSelectedItem().toString();

				// if (!USER.contains("Choose") && !DEVICE.contains("Choose")) {
				// util.convertJSON("find");
				if (btn.getText().equals("Stop")) {
					if (mTask != null) {
						mTask.cancel(true);
						try {
							mTimer.cancel();
						} catch (Exception e) {
							Toast.makeText(getApplicationContext(), "@@", 1000)
									.show();
						}
						mTask = null;
						btn.setText("Start");
					}
				} else {
					USER = "user1";
					DEVICE = "device1";
					try {
						count = 0;
						mTask = (AsyncTaskPage) new AsyncTaskPage(
								MainActivity.this, "find")
								.execute("http://10.3.9.147:1337/dataserie/findbyuseranddevice/"
										+ USER + "/" + DEVICE);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						Toast.makeText(getApplicationContext(),
								"Fail to get data", 1000).show();
					}
					// initGraph();
					// graphViewSeries1.resetData(new GraphViewDataInterface[]
					// {});
					// graphViewSeries2.resetData(new GraphViewDataInterface[]
					// {});
					// graphViewSeries3.resetData(new GraphViewDataInterface[]
					// {});
					// mTimer.start();
					// } else {
					// Toast.makeText(getApplicationContext(),
					// "Please choose user and device first!", 2000).show();
					// }
				}
			}
		});
	}

	private void initUserAndDevice() {

		// init User
		spnUser = (Spinner) findViewById(R.id.spnUser);
		userList = new ArrayList<String>();
		UserProfileDAO u = new UserProfileDAO(getApplicationContext());
		u.open();
		userList = u.getAllUserName();
		u.close();
		userList.add("Choose User");
		spnUser.setAdapter(new ItemAdapterSpin(getApplicationContext(),
				userList));
		spnUser.setSelection(userList.size() - 1);

		// init Device
		spnDevice = (Spinner) findViewById(R.id.spnDevice);
		deviceList = new ArrayList<String>();
		DeviceProfileDAO d = new DeviceProfileDAO(getApplicationContext());
		d.open();
		deviceList = d.getAllDeviceName();
		d.close();
		deviceList.add("Choose Device");
		spnDevice.setAdapter(new ItemAdapterSpin(getApplicationContext(),
				deviceList));
		spnDevice.setSelection(deviceList.size() - 1);
	}

	private void initDateTime() {
		cal = Calendar.getInstance();
		day = cal.get(Calendar.DAY_OF_WEEK);
		month = cal.get(Calendar.MONTH);
		year = cal.get(Calendar.YEAR);
		// init from date
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(
				((EditText) findViewById(R.id.edtFromDate)).getWindowToken(), 0);
		imm.hideSoftInputFromWindow(
				((EditText) findViewById(R.id.edtToDate)).getWindowToken(), 0);
		((EditText) findViewById(R.id.edtFromDate))
				.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						DialogFragment newFragment = new DatePickerFragment(
								"fromdate", day, month, year);
						newFragment.show(getSupportFragmentManager(),
								"datePicker");
					}
				});
		// init to date
		((EditText) findViewById(R.id.edtToDate))
				.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						DialogFragment newFragment = new DatePickerFragment(
								"todate", day, month, year);
						newFragment.show(getSupportFragmentManager(),
								"datePicker");
					}
				});
		((Button) findViewById(R.id.viewDetail))
				.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						util.showWarning();
						// Intent intent = new Intent(Intent.ACTION_CALL);
						// intent.setData(Uri.parse("tel:09999"));
						// startActivity(intent);
					}
				});
	}

	private void initGraph() {
		graphView = new LineGraphView(MainActivity.this, "Heart Beat Graph");
		graphView.getGraphViewStyle().setGridColor(Color.GRAY);
		graphView.getGraphViewStyle().setHorizontalLabelsColor(Color.GREEN);
		graphView.getGraphViewStyle().setHorizontalLabelsColor(Color.WHITE);
		graphView.getGraphViewStyle().setVerticalLabelsColor(Color.WHITE);
		graphView.getGraphViewStyle().setTextSize(17);
		graphView.getGraphViewStyle().setNumHorizontalLabels(8);
		graphView.getGraphViewStyle().setNumVerticalLabels(5);
		graphView.getGraphViewStyle().setVerticalLabelsWidth(50);
		graphView.setScalable(true);
		((LinearLayout) findViewById(R.id.lnlGraph)).addView(graphView);
	};

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		util.stopWarning();
		super.onPause();
	}

	@SuppressWarnings("deprecation")
	private void initGauge() {
		mGaugeView1 = (GaugeView) findViewById(R.id.gauge_view1);
		mGaugeView11 = (GaugeView) findViewById(R.id.gauge_view11);
		mGaugeView2 = (GaugeView) findViewById(R.id.gauge_view2);
		mGaugeView22 = (GaugeView) findViewById(R.id.gauge_view22);
		mGaugeView3 = (GaugeView) findViewById(R.id.gauge_view3);
		mGaugeView33 = (GaugeView) findViewById(R.id.gauge_view33);

		// fix width, height for each device
		mGaugeView1.requestLayout();
		mGaugeView2.requestLayout();
		mGaugeView3.requestLayout();
		mGaugeView1.getLayoutParams().height = getWindowManager()
				.getDefaultDisplay().getWidth() / 3;
		mGaugeView2.getLayoutParams().height = getWindowManager()
				.getDefaultDisplay().getWidth() / 3;
		mGaugeView3.getLayoutParams().height = getWindowManager()
				.getDefaultDisplay().getWidth() / 3;
		mGaugeView1.setTargetValue(0);
		mGaugeView11.setTargetValue(0);
		mGaugeView2.setTargetValue(0);
		mGaugeView22.setTargetValue(0);
		mGaugeView3.setTargetValue(0);
		mGaugeView33.setTargetValue(0);
	}

	private int count = 0;
	private final CountDownTimer mTimer = new CountDownTimer(300000, 1000) {

		@Override
		public void onTick(final long millisUntilFinished) {
			count++;
			// int temp1 = RAND.nextInt(201);
			// int temp2 = RAND.nextInt(201);
			// int temp3 = RAND.nextInt(201);
			mGaugeView1.setTargetValue(v1.get(count - 1));
			mGaugeView11.setTargetValue(v1.get(count - 1));
			mGaugeView2.setTargetValue(v2.get(count - 1));
			mGaugeView22.setTargetValue(v2.get(count - 1));
			mGaugeView3.setTargetValue(v3.get(count - 1));
			mGaugeView33.setTargetValue(v3.get(count - 1));

			graphViewSeries1.appendData(
					new GraphViewData(count, v1.get(count - 1)), true,
					v1.size());
			graphViewSeries2.appendData(
					new GraphViewData(count, v2.get(count - 1)), true,
					v1.size());
			graphViewSeries3.appendData(
					new GraphViewData(count, v3.get(count - 1)), true,
					v1.size());
			graphView.setViewPort(1, count - 1);
		
			DataRecordDAO d = new DataRecordDAO(MainActivity.this);
			d.open();
			dataSize = d.getSize();
			Log.d("status", "count / datasize: " +count + " / "  +dataSize);
			if (count > dataSize) {
				d.insertDataRecord(v1.get(count - 1), v2.get(count - 1),
						v3.get(count - 1), listTime.get(count - 1));
			}
			d.close();
			if (count == v1.size()) {
				btn.setText("Start");
				count = 0;
				mTimer.cancel();
			}

		}

		@Override
		public void onFinish() {
			btn.setText("Start");
			count = 0;
		}
	};

	public void setResult(List<Integer> listV1, List<Integer> listV2,
			List<Integer> listV3, List<String> listTime1) {
		// TODO Auto-generated method stub
		if (listV1.size() == 0) {
			Toast.makeText(getApplicationContext(),
					"No data found in your device, check your connection", 2000)
					.show();
		} else {
			v1 = listV1;
			v2 = listV2;
			v3 = listV3;
			this.listTime = listTime1;
			graphViewSeries1 = new GraphViewSeries("v1", null,
					new GraphViewData[] { new GraphViewData(0, listV1.get(0)) });
			graphViewSeries2 = new GraphViewSeries("v2", null,
					new GraphViewData[] { new GraphViewData(0, listV2.get(0)) });
			graphViewSeries3 = new GraphViewSeries(
					"v3",
					null,
					new GraphViewData[] { new GraphViewData(0, listV3.get(0)), });
			graphViewSeries1.getStyle().thickness = 2;
			graphViewSeries2.getStyle().thickness = 2;
			graphViewSeries3.getStyle().thickness = 2;
			graphViewSeries1.getStyle().color = Color.RED;
			graphViewSeries2.getStyle().color = Color.BLUE;
			graphViewSeries3.getStyle().color = Color.MAGENTA;
			graphView.addSeries(graphViewSeries1);
			graphView.addSeries(graphViewSeries2);
			graphView.addSeries(graphViewSeries3);

			graphViewSeries1.resetData(new GraphViewDataInterface[] {});
			graphViewSeries2.resetData(new GraphViewDataInterface[] {});
			graphViewSeries3.resetData(new GraphViewDataInterface[] {});
			mTimer.start();
		}
	}
}
